<template>
  <el-dialog
    title="身份验证"
    width="260px"
    top="15%"
    :visible.sync="isVisible"
    :modal-append-to-body="false"
    :center="true"
    :close-on-click-modal="false"
    :before-close="handleClose"
  >
    <div class="verifyBox">
      <img :src="verifyImg" />
      <el-button type="text" @click="getCaptcha">换一张</el-button>
    </div>
    <el-form
      ref="verifyFormRef"
      :model="verifyForm"
      :rules="verifyRules"
      class="verifyForm"
    >
      <el-form-item prop="captcha">
        <el-input v-model="verifyForm.captcha" placeholder="请输入验证码" />
      </el-form-item>
    </el-form>
    <el-button type="primary" class="confirmButton" @click="handleSubmit"
      >确定</el-button
    >
  </el-dialog>
</template>

<script>
import { getImgCaptcha } from "@/apis/login";
export default {
  name: "verifyDialog",
  props: {
    isVisible: {
      type: Boolean,
      default: false,
      required: true
    }
  },
  data() {
    return {
      verifyForm: {
        captcha: ""
      },
      verifyRules: {
        captcha: [{ required: true, message: "请输入验证码", trigger: "blur" }]
      },
      verifyImg: ""
    };
  },
  watch: {
    isVisible: {
      handler(newVal) {
        if (newVal) {
          this.verifyForm.captcha = "";
          this.$nextTick(() => {
            if (this.$refs["verifyFormRef"]) {
              this.$refs["verifyFormRef"].clearValidate();
            }
          });
          this.getCaptcha();
        }
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    async getCaptcha() {
      // 获取新验证码之前清空之前的验证码
      if (this.verifyForm.captcha) {
        this.verifyForm.captcha = "";
      }
      try {
        const res = await getImgCaptcha({ customApi: this.$attrs.customApi });
        this.verifyImg = res.image;
        this.verifyKey = res.verKey;
      } catch (err) {
        console.error(err);
      }
    },
    handleClose() {
      this.$emit("close");
    },
    handleSubmit() {
      this.$refs["verifyFormRef"].validate((valid) => {
        if (valid) {
          this.$emit("close", this.verifyForm.captcha, this.verifyKey);
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .el-dialog {
  border-radius: 4px;
  &__wrapper {
    overflow: hidden;
  }
  &__header {
    text-align: left;
  }
  &__title {
    color: #333333;
    font-weight: 600;
    font-size: 16px;
  }
}
.verifyBox {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  img {
    width: 122px;
  }
}
.confirmButton {
  width: 100%;
}
</style>
